package com.syg.idempotent.config;

import com.syg.idempotent.IdempotentAspect;
import com.syg.idempotent.IdempotentService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;

/**
 * @author ps
 */
@Configuration
@EnableConfigurationProperties({IdempotentProperties.class})
@ConditionalOnProperty(
        value = {"syg.boot.idempotent.enabled"},
        matchIfMissing = false
)
public class IdempotentAutoConfiguration implements BeanFactoryAware {

    @Autowired
    private IdempotentProperties idempotentProperties;

    private BeanFactory beanFactory;

    public IdempotentService idempotentService() {
        DataSource dataSource = this.getDataSource();
        IdempotentService service = new IdempotentService(dataSource, this.idempotentProperties.getIdempotentTableName(), this.idempotentProperties.getSplitTableSuffix());
        return service;
    }

    @Bean
    public IdempotentAspect logAspcet() {
        return new IdempotentAspect(this.idempotentService());
    }

    public DataSource getDataSource() {
        DataSource dataSource = null;
        String dataSourceName = this.idempotentProperties.getDataSourceName();
        if (null != dataSourceName && dataSourceName.length() > 0) {
            dataSource = (DataSource)this.beanFactory.getBean(dataSourceName);
            if (null == dataSource) {
                throw new RuntimeException(dataSourceName + "数据源不存在");
            }
        }

        if (null == dataSource) {
            dataSource = this.beanFactory.getBean(DataSource.class);
        }

        return dataSource;
    }


    @PostConstruct
    public void init() {

    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {

    }
}
